package org.rcy.framework.job.elastic;

import com.dangdang.ddframe.job.lite.internal.instance.InstanceService;
import com.dangdang.ddframe.job.lite.internal.server.ServerService;
import com.dangdang.ddframe.job.reg.zookeeper.ZookeeperRegistryCenter;
import com.dangdang.ddframe.job.util.env.IpUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Iterator;

public class JobShutdownHook {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    private JobManager jobManager;
    private ZookeeperRegistryCenter regCenter;

    public JobShutdownHook(JobManager jobManager) {
        this.jobManager = jobManager;
    }

    public void addHook() {
        this.logger.info("Add shutdown hook.");
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            this.logger.info("Cleaning job servers");
            regCenter.init();
            Iterator var2 = this.jobManager.getJobNames().iterator();

            while(var2.hasNext()) {
                String jobName = (String)var2.next();
                String serverIp = IpUtils.getIp();
                this.logger.info("Cleaning job server, {}", jobName);
                String serverPath = String.format("/%s/%s/%s", jobName, "servers", serverIp);
                ServerService serverService = new ServerService(regCenter, jobName);
                (new InstanceService(regCenter, jobName)).removeInstance();
                if (!serverService.isAvailableServer(serverIp)) {
                    this.logger.info("Server {} is not available. Ready to remove it.", serverPath);
                    regCenter.remove(serverPath);
                    this.logger.info("Server {} has been removed.", serverPath);
                }
            }

            regCenter.close();
        }));
    }
}